package com.ad.dao;

import java.util.ArrayList;
import java.util.List;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.ad.hibernate.Region;
import com.ad.system.Common;

public class RegionDao extends HibernateDaoSupport implements IRegionDao {

	@SuppressWarnings("unchecked")
	@Override
	public List<Region> getChildren(String regionId) {
		List<Region> result = null;
		if (!Common.isEmpty(regionId)) {
			String hql = "";
			// 如果以00结尾，那么表示这是个城市的ID号;
			// 如果以0000结尾,表示这是个省的ID号；如果两者都不是，则肯定无子区域
			if (regionId.endsWith("00")) {
				hql = "from Region where cityId=?";
			} else if (regionId.endsWith("0000")) {
				hql = "from Region where provinceId=?";
			} else {
				return null;
			}
			result = this.getHibernateTemplate().find(hql,
					getParentId(regionId));
		}
		return result;
	}

	@SuppressWarnings("unchecked")
	public List<Region> getBrother(String areaId) {
		List<Region> result = null;
		if (!Common.isEmpty(areaId)) {
			String hql = "";
			// 如果以00结尾，那么表示这是个城市的ID号
			if (areaId.endsWith("00")) {
				hql = "from Region where provinceId=?";
			} else {
				hql = "from Region where cityId=?";
			}
			result = this.getHibernateTemplate().find(hql, getParentId(areaId));
		}
		return result;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Region> getRegionByName(String name) {
		List<Region> result = null;
		if (!Common.isEmpty(name)) {
			result = this
					.getHibernateTemplate()
					.find(
							"from Region where LOCATE(?,cityName)>0 or LOCATE(?,provinceName)>0",
							new Object[] { name, name });
		}
		return result;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Region getReiongById(String id) {
		Region region = null;
		if (Common.isEmpty(id)) {
			List<Region> list = this.getHibernateTemplate().find(
					"from Region where id=?", id);
			if (!Common.isEmpty(list) && list.size() == 1) {
				region = list.get(0);
			}
		}
		return region;
	}

	public String getParentId(String regionId) {
		String parentId = null;
		if (!Common.isEmpty(regionId) && regionId.length() == 6) {
			String lastTwo = regionId.substring(5, 6);
			if (lastTwo.equals("00")) {
				parentId = regionId.substring(0, 2) + "0000";
			} else {
				parentId = regionId.substring(0, 4) + "00";
			}
		}
		return parentId;
	}

	@Override
	public List<String> getParentName(String name) {
		List<Region> list = getRegionByName(name);
		List<String> result = new ArrayList<String>();
		for (int i = 0; i < list.size(); i++) {
			Region r = list.get(i);
			String cityName = r.getCityName();
			String provinceName = r.getProvinceName();
			if (r.getAreaName().contains(name)) {
				if (!result.contains(cityName)) {
					result.add(cityName);
				}
			}
			if (cityName.contains(name)) {
				if (!result.contains(provinceName)) {
					result.add(provinceName);
				}
			}
		}
		return result;
	}

}
